<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\common\model\Auth;
use app\user\model\User as UserModel;
use app\mill\model\Client as ClientModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Finance as FinanceModel;
use app\mill\model\Give as GiveModel;
use app\mill\model\Audit as AuditModel;
use app\admin\model\Config as ConfigModel;
use app\mill\model\Contract as ContractModel;
use app\wh\model\Material as MaterialModel;
use app\mill\model\Log as LogModel;
use think\Db;

/**
 * 账单控制器
 * @package app\admin\controller
 */
class Finance extends Admin
{
    public $_status = [
        -1      =>  '未通过',
        0       =>  '待审核',
        1       =>  '已审核',
    ];
    /**
     * 列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['pid','=',0];
        // 数据列表
        $data_list = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*')
            //->leftJoin('mill_order o','o.id=f.order_pid')
            //->leftJoin('mill_client c','c.id=o.client_id')
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate()
            ->each(function ($v){

                //获取账单应收款信息
                $finance = FinanceModel::financeInfo($v['order_pid']);
                $v = array_merge($v,$finance);

                $v['row_area'] += $v['address_area'];
                $v['address_money'] += $v['audit_money'] + $v['audit_no_money'];

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('财务管理（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_finance') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '工程号', 'like'],
                ['text:2', 'f.engineering', '工程名称', 'like'],
                ['text:2', 'f.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['note', '完成状态'],
                //['note', '备注','popover'],
                ['sum_money', '工程总金额'],
                ['opening_money', '期初结余'],
                ['row_area', '发货量'],
                ['address_money', '发货金额'],
                ['deposit_money', '定金'],
                ['receivable_money', '回款'],
                ['rece_money', '应收款项金额'],
                ['money', '实收款项金额'],
                ['rece_time', '预计收款时间','date'],
                ['handle', '经办人'],
                ['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                //['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('edit1',['title' => '新增','href' => url('add'),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '99%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('edit1',['title' => '编辑','href' => url('edit',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '99%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->addRightButton('account', ['title' => '子账单', 'href' => url('account', [ 'pid' => '__id__']), 'icon' => ''])
            ->addRightButton('logList', ['title' => '收款记录', 'href' => url('logList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            ->addRightButton('invoiceList', ['title' => '开票记录', 'href' => url('invoiceList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 应收汇总统计
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function collect()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['pid','=',0];
        // 数据列表
        $data_list = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*')
            ->where($map)
            //->group('f.id')
            ->order('f.rece_time desc')
            ->paginate()
            ->each(function ($v){

                //获取账单应收款信息
                $finance = FinanceModel::financeInfo($v['order_pid']);
                $v = array_merge($v,$finance);
                $v['row_area'] += $v['address_area'];
                if(empty($v['order_id'])){
                    //$v['order_money'] = $v['sum_money'];
                    //$v['rece_money_sum'] = $v['rece_money'];
                }

                //当前时间
                $v['now_time'] = strtotime(date('Y-m-d'));
                //天数
                $v['day'] = 0;
                //最后一次发货时间
                if(!empty($v['address_time'])){
                    $v['address_time'] = strtotime(date('Y-m-d',$v['address_time']));
                    //天数
                    $v['day'] = intval(($v['now_time']-$v['address_time'])/86400);
                }

                //90天以内
                $v['day0'] = 0;
                //90-180天
                $v['day1'] = 0;
                //180-360天
                $v['day2'] = 0;
                //一年至两年
                $v['day3'] = 0;
                //两年至三年
                $v['day4'] = 0;
                //三年以上
                $v['day5'] = 0;
                if($v['day'] <= 90)$v['day0'] = $v['rece_money_sum'];
                elseif($v['day'] >= 90 && $v['day'] <= 180)$v['day1'] = $v['rece_money_sum'];
                elseif($v['day'] >= 180 && $v['day'] <= 360)$v['day2'] = $v['rece_money_sum'];
                elseif($v['day'] >= 360 && $v['day'] <= 720)$v['day3'] = $v['rece_money_sum'];
                elseif($v['day'] >= 720 && $v['day'] <= 1080)$v['day4'] = $v['rece_money_sum'];
                else $v['day5'] = $v['rece_money_sum'];

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('应收汇总统计') // 页面标题
            ->setTableName('mill_finance') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '工程号', 'like'],
                ['text:2', 'f.engineering', '工程名称', 'like'],
                ['text:2', 'f.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['row_area', '发货量'],
                ['deposit_money', '定金'],
                ['order_money', '货款(元)'],
                ['opening_money', '期初结余(元)'],
                ['receivable_money', '回款(元)'],
                ['rece_money_sum', '应收款(元)'],
                ['html_config', '付款节点'],
                ['invoice_money', '已开票金额'],
                ['audit_no_money', '未对账金额'],
                ['audit_money', '对账金额'],
                ['address_time', '最后一次发货时间','date'],
                //['now_time', '当前时间','date'],
                ['day', '天数'],
                ['day0', '90天以内'],
                ['day1', '90-180天'],
                ['day2', '180-360天'],
                ['day3', '一年至两年'],
                ['day4', '两年至三年'],
                ['day5', '三年以上'],

                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('account', ['title' => '子账单', 'href' => url('account', [ 'pid' => '__id__']), 'icon' => ''])
            ->addRightButton('audit', ['title' => '对账单', 'href' => url('mill/audit/index')."?_s=f.order_sn=__order_sn__&_o=f.order_sn=like", 'icon' => ''])
            ->addRightButton('logList', ['title' => '收款记录', 'href' => url('logList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            ->addRightButton('invoiceList', ['title' => '开票记录', 'href' => url('invoiceList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 待收款账单
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function payment()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['pid','>',0];
        // 数据列表
        $data_list = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*')
            ->where($map)
            ->group('f.id')
            ->order('f.rece_time desc')
            ->paginate()
            ->each(function ($v){

                //获取账单应收款信息
                $finance = FinanceModel::financeInfo($v['order_pid']);
                $v = array_merge($v,$finance);

                //最后一次发货时间
                if(!empty($v['address_time']))$v['address_time'] = strtotime(date('Y-m-d',$v['address_time']));
                //当前时间
                $v['now_time'] = strtotime(date('Y-m-d'));
                //天数
                $v['day'] = intval(($v['now_time']-$v['address_time'])/86400);

                //90天以内
                $v['day0'] = 0;
                //90-180天
                $v['day1'] = 0;
                //180-360天
                $v['day2'] = 0;
                //一年至两年
                $v['day3'] = 0;
                //两年至三年
                $v['day4'] = 0;
                //三年以上
                $v['day5'] = 0;
                if($v['day'] <= 90)$v['day0'] = $v['rece_money_sum'];
                elseif($v['day'] >= 90 && $v['day'] <= 180)$v['day1'] = $v['rece_money_sum'];
                elseif($v['day'] >= 180 && $v['day'] <= 360)$v['day2'] = $v['rece_money_sum'];
                elseif($v['day'] >= 360 && $v['day'] <= 720)$v['day3'] = $v['rece_money_sum'];
                elseif($v['day'] >= 720 && $v['day'] <= 1080)$v['day4'] = $v['rece_money_sum'];
                else $v['day5'] = $v['rece_money_sum'];

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('待收款账单') // 页面标题
            ->setTableName('mill_finance') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '工程号', 'like'],
                ['text:2', 'f.engineering', '工程名称', 'like'],
                ['text:2', 'f.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['row_area', '发货量'],
                //['deposit_money', '定金'],
                //['order_money', '货款(元)'],
                //['receivable_money', '回款(元)'],
                ['rece_money', '应收款(元)'],
                ['money', '实收款(元)'],
                ['html_config', '付款节点'],
                //['invoice_money', '已开票金额'],
                //['audit_no_money', '未对账金额'],
                //['audit_money', '对账金额'],
                ['address_time', '最后一次发货时间','date'],
                //['now_time', '当前时间','date'],
                //['day', '天数'],
                //['day0', '90天以内'],
                //['day1', '90-180天'],
                //['day2', '180-360天'],
                //['day3', '一年至两年'],
                //['day4', '两年至三年'],
                //['day5', '三年以上'],
                ['rece_time', '预计收款时间','date'],

                ['right_button', '操作', 'btn']
            ])
            //->addRightButton('account', ['title' => '子账单', 'href' => url('account', [ 'pid' => '__id__']), 'icon' => ''])
            //->addRightButton('audit', ['title' => '对账单', 'href' => url('mill/audit/index')."?_s=f.order_sn=__order_sn__&_o=f.order_sn=like", 'icon' => ''])
            //->addRightButton('logList', ['title' => '收款记录', 'href' => url('logList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            //->addRightButton('invoiceList', ['title' => '开票记录', 'href' => url('invoiceList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        $pid = input('pid');
        $info = [
            'is_pid'        =>  0,
            'order_pid'     =>  0,
            'rece_time'     =>  time(),
        ];
        if(!empty($pid)){
            $finance = Db::name('mill_finance')->where(['id'=>$pid])->find();
            $info['order_pid'] = $finance['order_pid'];
            $info['order_sn'] = $finance['order_sn'];
            $info['engineering'] = $finance['engineering'];
            $info['company'] = $finance['company'];
            $info['handle'] = $finance['handle'];

            $info['pid'] = $pid;
            $info['is_pid'] = 1;
        }

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $result = $this->validate($data, 'Finance');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['rece_time'] = strtotime($data['rece_time']);
            $data['create_time'] = time();
            $data['update_time'] = time();

            if(!empty($pid))$data['money'] = $data['rece_money'];

            $re = Db::name('mill_finance')->insertGetId($data);
            if ($re){

                //如果是新增的子账单，则更新实收金额
                if(!empty($pid))Db::name('mill_finance')->where(['id'=>$pid])->setInc('money',$data['money']);

                $this->success('操作成功','','_parent_reload');
            }
            $this->error('操作失败');
        }


        return ZBuilder::make('form')
            ->setPageTitle('新增账单') // 页面标题
            ->addHidden('pid')
            ->addHidden('is_pid')
            ->addFormItems([ // 批量添加表单项
                ['text:||||must', 'order_sn', '工程号'],
                ['text:||||must', 'engineering', '工程名称'],
                ['text:||||must', 'company', '客户公司'],
                ['text:||||must', 'handle', '经办人'],
                ['text:||||must', 'sum_money', '工程总金额'],
                ['text:||||must', 'opening_money', '期初结余'],
                ['text:12||||must', 'deposit_money', '定金'],
                ['text:||||must', 'address_area', '发货量'],
                ['text:||||must', 'address_money', '发货金额'],
                ['text:||||must', 'rece_money', '应收款项金额'],
                ['date:||||must', 'rece_time', '预计收款时间'],
                ['text:||||must', 'late_money', '滞纳金'],
                ['date:||||must', 'late_time', '滞纳金退还时间'],
                ['textarea:12||||must', 'note', '项目数据(完成状态)'],

            ])
            ->setTrigger('is_pid','0','sum_money,opening_money,late_money,late_time,deposit_money,address_area,address_money')
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 编辑
     * @param null $id
     * @return mixed
     */
    public function edit($id=null)
    {
        $id = input('id');
        $info = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*')
            ->where(['f.id'=>$id])
            ->find();
        $info['is_pid'] = 1;
        if(empty($info['pid']))$info['is_pid'] = 0;

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $result = $this->validate($data, 'Finance');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['rece_time'] = strtotime($data['rece_time']);
            $data['update_time'] = time();

            $re = Db::name('mill_finance')->update($data);
            if ($re) $this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }


        return ZBuilder::make('form')
            ->setPageTitle('编辑账单') // 页面标题
            ->addHidden('is_pid')
            /*->addFormItems([ // 批量添加表单项
                ['text:||||must', 'order_sn', '工程号'],
                ['text:||||must', 'engineering', '工程名称'],
                ['text:||||must', 'company', '客户公司'],
                ['text:||||must', 'handle', '经办人'],
                ['text:||||must', 'opening_money', '期初结余'],
                ['text:||||must', 'rece_money', '应收款项金额'],
                ['date:||||must', 'rece_time', '预计收款时间'],
                ['textarea:12||||must', 'note', '项目数据(完成状态)'],

            ])*/
            ->addFormItems([ // 批量添加表单项
                ['text:||||must', 'order_sn', '工程号'],
                ['text:||||must', 'engineering', '工程名称'],
                ['text:||||must', 'company', '客户公司'],
                ['text:||||must', 'handle', '经办人'],
                ['text:||||must', 'sum_money', '工程总金额'],
                ['text:||||must', 'opening_money', '期初结余'],
                ['text:12||||must', 'deposit_money', '定金'],
                ['text:||||must', 'address_area', '发货量'],
                ['text:||||must', 'address_money', '发货金额'],
                ['text:||||must', 'rece_money', '应收款项金额'],
                ['date:||||must', 'rece_time', '预计收款时间'],
                ['text:||||must', 'late_money', '滞纳金'],
                ['date:||||must', 'late_time', '滞纳金退还时间'],
                ['textarea:12||||must', 'note', '项目数据(完成状态)'],

            ])
            ->setTrigger('is_pid','0','sum_money,opening_money,late_money,late_time,deposit_money,address_area,address_money')
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 删除
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }
    /**
     * 启用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }
    /**
     * 禁用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }
    /**
     * 待审核财务列表页
     * @return mixed
     */
    public function examine()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        // 数据列表
        $data_list = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*')
            ->where([['f.status','<>','1'],['f.pid','=',0]])
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate();
        //待审核
        $map0[] = ['status','eq','0'];
        $total0 = Db::name('mill_finance')->alias('f')->where($map0)->count();
        //未通过
        $map01[] = ['status','eq','-1'];
        $total01 = Db::name('mill_finance')->alias('f')->where($map01)->count();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('财务审核（待审核'.$total0.'/未通过'.$total01.'）') // 页面标题
            ->setTableName('mill_finance') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '工程号', 'like'],
                ['text:2', 'f.engineering', '工程名称', 'like'],
                ['text:2', 'f.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['note', '完成状态'],
                //['note', '备注','popover'],
                ['rece_money', '应收款项金额'],
                ['rece_time', '预计收款时间','date'],
                ['handle', '经办人'],
                ['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('backEnable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__'])."?fieldv=status|1",'class'=>'btn btn-default ajax-get','icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'status']),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['status' => ['in', '1']], '', 'backEnable,notDisable')
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板

    }
    /**
     * 审核
     */
    public function backEnable()
    {

        $id = input('param.id');
        $fieldv = input('param.fieldv');
        $fieldv = explode('|',$fieldv);

        $info = Db::name('mill_finance')->where('id', $id)->find();

        if (false === Db::name('mill_finance')->where('id', $id)->update([$fieldv[0]=>$fieldv[1]])) {
            $this->error('审核失败，工程ID：'.$id);
        }
        //审核人员
        Db::name('mill_finance')->where('id', $id)->update([$fieldv[0].'_verify_uid'=>UID]);
        //审核时间
        Db::name('mill_finance')->where('id', $id)->update([$fieldv[0].'_time'=>time()]);

        //推送消息
        $status_str = '审核';
        $content = "工程编号<span class='text-primary'>[{$info['order_sn']}]</span>{$status_str}通过";
        $href = admin_url('index')."?_s=f.order_sn={$info['order_sn']}&_o=f.order_sn=like";
        //LogModel::send_message("财务{$status_str}",$content,$href);

        $this->success('提交成功', null, '_parent_reload');
    }
    /**
     * 审核不通过
     */
    public function notDisable()
    {
        $field = input('param.field');
        if ($this->request->isPost()) {
            $data = input();
            $id = input('param.id');
            if (false === Db::name('mill_finance')->where('id', $id)->update([$field=>-1])) {
                $this->error('审核失败，工程ID：'.$id);
            }
            if(!empty($data[$field.'_note']))Db::name('mill_finance')->where('id', $id)->update([$field.'_note'=>$data[$field.'_note']]);
            //审核人员
            Db::name('mill_finance')->where('id', $id)->update([$field.'_verify_uid'=>UID]);
            //审核时间
            Db::name('mill_finance')->where('id', $id)->update([$field.'_time'=>time()]);

            $this->success('操作成功', null, '_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('审核不通过原因') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['textarea', $field.'_note', '[:请输入审核不通过原因]'],
            ])
            ->layout([$field.'_note'=>12])
            ->fetch();
    }

    /**
     * 子账单列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function account()
    {
        $pid = input('pid');
        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['pid','=',$pid];
        // 数据列表
        $data_list = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*')
            //->leftJoin('mill_order o','o.id=f.order_pid')
            //->leftJoin('mill_client c','c.id=o.client_id')
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('财务管理（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_finance') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '档案号', 'like'],
                ['text:2', 'f.engineering', '工程名称', 'like'],
                ['text:2', 'f.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '档案号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['note', '完成状态'],
                //['note', '备注','popover'],
                ['rece_money', '应收款项金额'],
                ['rece_time', '预计收款时间','date'],
                ['handle', '经办人'],
                /*['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],*/
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('add',['title' => '新增子账单','href' => url('add',['pid'=>$pid]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['新增子账单', 'font-size:24px;text-align: center;']])
            ->addRightButton('edit1',['title' => '编辑','href' => url('edit',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->addRightButton('accountLog', ['title' => '调账', 'href' => url('accountLog', [ 'finance_id' => '__id__']), 'icon' => ''])
            //->addRightButton('logList', ['title' => '收款记录', 'href' => url('logList', [ 'pid' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            //->addRightButton('invoiceList', ['title' => '开票记录', 'href' => url('invoiceList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 调账列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function accountLog()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $finance_id = input('finance_id');
        $map = $this->getMap();
        $map[] = ['l.finance_id','=',$finance_id];

        // 数据列表
        $data_list = Db::name('mill_finance_account')
            ->alias('l')
            ->field('l.*,o.engineering,c.company,o.archives_sn')
            ->leftJoin('mill_order o','o.id=l.order_pid')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where($map)
            ->group('l.id')
            ->order('l.id desc')
            ->paginate()
            ->each(function ($v){
                $v['money_str'] = FinanceModel::getMoneyStr($v['type'],$v['money'],true);
                $v['money'] = FinanceModel::getMoneyStr($v['type'],$v['money']);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('调账管理（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_finance_account') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                //['text:2', 'f.order_sn', '工程编号', 'like'],
                //['text:2', 'o.engineering', '工程名称', 'like'],
                //['text:2', 'c.company', '客户公司', 'like'],
                //['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['money_str','调账收入(元)'],
                ['note', '调账说明'],
                ['handle', '经办人'],
                ['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('accountAdd',['title' => '新增','href' => url('accountAdd',['finance_id'=>$finance_id]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('accountEdit',['title' => '编辑','href' => url('accountAdd',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function accountAdd()
    {
        $id = input('id');
        $finance_id = input('finance_id');

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $rule = [
                'finance_id|标题' => 'require',
                'type|收入类型' => 'require',
                'money|调账收入' => 'require',
                'handle|经办人' => 'require',
                'note|调账说明' => 'require',
            ];
            $result = $this->validate($data, $rule);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['update_time'] = time();

            if($id)$re = Db::name('mill_finance_account')->where(['id'=>$id])->update($data);
            else{
                $data['create_time'] = time();
                $re = Db::name('mill_finance_account')->insert($data);
            }

            if ($re) $this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        if($id)$info = Db::name('mill_finance_account')->where(['id'=>$id])->find();
        else{
            $finance = Db::name('mill_finance')->where(['id'=>$finance_id])->find();

            $info = [
                'finance_id'    =>  $finance_id,
                'order_pid'     =>  $finance['order_pid'],
            ];
        }

        return ZBuilder::make('form')
            ->setPageTitle('新增账单') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden','finance_id'],
                ['hidden','order_pid'],
                ['radio:||||must','type', '收入类型','',['调减收入','调增收入'],1],
                ['text:||||must', 'money', '调账收入'],
                ['text:||||must', 'handle', '经办人'],
                ['textarea:||||must', 'note', '调账说明'],

            ])
            ->setFormData($info)
            ->fetch();
    }

    /**
     * 待审核调账列表页
     * @return mixed
     */
    public function accountExamine()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['pid','>',0];

        // 获取查询条件
        $map0 = $map01 = $map;

        // 数据列表
        $data_list = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*,o.engineering,c.company,o.order_sn')
            ->leftJoin('mill_order o','o.id=f.order_pid')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where([['f.status','<>','1']])
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate()
            ->each(function ($v){
                $v['money_str'] = FinanceModel::getMoneyStr($v['type'],$v['money'],true);
                $v['money'] = FinanceModel::getMoneyStr($v['type'],$v['money']);

                return $v;
            })
        ;

        //待审核
        $map0[] = ['status','eq','0'];
        $total0 = Db::name('mill_finance')->where($map0)->count();
        //未通过
        $map01[] = ['status','eq','-1'];
        $total01 = Db::name('mill_finance')->where($map01)->count();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('待审核调账（待审核'.$total0.'/未通过'.$total01.'）') // 页面标题
            ->setTableName('mill_finance') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'o.order_sn', '工程号', 'like'],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['text:2', 'c.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['money_str','调账收入(元)'],
                ['note', '调账说明'],
                ['handle', '经办人'],
                ['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('accountEnable',['title' => '审核通过','href' => url('accountEnable',['id' => '__id__','rece_money'=>'__money__'])."?fieldv=status|1",'class'=>'btn btn-default ajax-get','icon'=>''])
            ->addRightButton('accountDisable',['title' => '审核不通过','href' => url('accountDisable',['id' => '__id__','field'=>'status']),'class'=>'btn btn-primary','icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['status' => ['in', '1']], '', 'accountEnable,accountDisable')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 调账审核
     */
    public function accountEnable()
    {

        $id = input('param.id');
        $fieldv = input('param.fieldv');
        $fieldv = explode('|',$fieldv);
        if (false === Db::name('mill_finance')->where('id', $id)->update([$fieldv[0]=>$fieldv[1]])) {
            $this->error('审核失败，工程ID：'.$id);
        }
        //审核人员
        Db::name('mill_finance')->where('id', $id)->update([$fieldv[0].'_verify_uid'=>UID]);
        //审核时间
        Db::name('mill_finance')->where('id', $id)->update([$fieldv[0].'_time'=>time()]);

        //额外字段更新
        $rece_money = input('rece_money');
        if($rece_money){
            $pid = Db::name('mill_finance')->where(['id'=>$id])->value('pid');
            Db::name('mill_finance')->where('id', $pid)->setInc('rece_money',$rece_money);
        }

        $this->success('提交成功', null, '_parent_reload');
    }
    /**
     * 调账审核不通过
     */
    public function accountDisable()
    {
        $field = input('param.field');
        if ($this->request->isPost()) {
            $data = input();
            $id = input('param.id');
            if (false === Db::name('mill_finance')->where('id', $id)->update([$field=>-1])) {
                $this->error('审核失败，工程ID：'.$id);
            }
            if(!empty($data[$field.'_note']))Db::name('mill_finance')->where('id', $id)->update([$field.'_note'=>$data[$field.'_note']]);
            //审核人员
            Db::name('mill_finance')->where('id', $id)->update([$field.'_verify_uid'=>UID]);
            //审核时间
            Db::name('mill_finance')->where('id', $id)->update([$field.'_time'=>time()]);

            $this->success('操作成功', null, '_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('审核不通过原因') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['textarea', $field.'_note', '[:请输入审核不通过原因]'],
            ])
            ->layout([$field.'_note'=>12])
            ->fetch();
    }

    /**
     * 设定面积表初始价格列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesPriceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['o.archives_status','=',2];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,sum(a.number) as number_sum,sum(a.one_area*a.number) as area_sum,o.id as ip_id')
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->where($map)
            ->group('o.id')
            ->order('o.archives_status_time desc,o.id desc')
            ->paginate();

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('批次价格') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'a.archives_sn', '档案号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum', '产品总量'],
                ['area_sum', '总面积'],
                //['initial_price_status','计价状态','callback',function($value, $data){
                //    //$value = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$value])->value('id');
                //    //$value = empty($value)?0:1;
                //    //$str = FinanceModel::$initial_price_status[$value];
                //    $status = OrderModel::status_tag($value,FinanceModel::$initial_price_status[$value]);
                //    if($value == -1){
                //        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['initial_price_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                //    }
                //    return $status;
                //},'__data__'],
                ['right_button', '操作', 'btn']
            ])
            //->addRightButton('archivesPrice',['title' => '计价','href' => url('mill/finance/archivesPrice',['order_id' => '__id__']),'class'=>'btn btn-default','icon'=>''])
            ->addRightButton('archivesPrice',['title' => '查看','href' => url('mill/finance/archivesPrice',['order_id' => '__id__']),'class'=>'btn btn-default','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 设定面积表初始价格
     * @return mixed
     */
    public function archivesPrice()
    {

        if(empty($order_id))$order_id = input('order_id');//指定工程
        if(empty($order_id))$this->error('错误操作');

        $table_arr = FinanceModel::fromArchivesShow($order_id);

        $where[] = ['a.order_id','=',$order_id];

        //单价设置
        $order = Db::name('mill_order')->where(['id'=>$order_id])->find();
        $title = "{$order['engineering']} {$order['archives_sn']} 面积表价格";

        $sum_number = 0;//合计数量
        $sum_area = 0;//合计面积
        $sum_price = 0;//合计总金额

        //表头
        $field_arr = [
            'sort'          =>  '序号',
            'page'          =>  '图号',
            'model_sn'      =>  '编号',
            'thickness'     =>  '板厚(MM)',
            'color'         =>  '颜色',
            'model'         =>  '板型',
            'number'        =>  '数量',
            'row_area'      =>  '合计面积(M²)',
            'basic_price'   =>  '板厚基价',
            'plate_price'   =>  '板型加价',
            'color_price'   =>  '颜色加价',
            'price'         =>  '单价',
            'sum_price'     =>  '金额',
        ];

        $table_head = [array_values($field_arr)];
        $table_data = [];

        $field = array_keys($field_arr);
        foreach ($field as &$f_k){
            if($f_k == 'sum_price')$f_k = "(row_area*price) as sum_price";
        }
        $field = implode(',',$field);

        $list = Db::name('mill_order_archives')
            ->field($field)
            ->where(['order_id'=>$order_id])
            ->orderRaw('convert(sort,signed)')
            ->select();
        foreach ($list as $v){

            $v['sum_price'] = round(floatval($v['sum_price']),2);

            $sum_number += floatval($v['number']);
            $sum_area += floatval($v['row_area']);
            $sum_price += floatval($v['sum_price']);

            $table_data[] = array_values($v);
        }

        //合计开槽(M)
        $slot['row_area'] = Db::name('mill_order_archives')->where(['order_id'=>$order_id])->sum('slot');
        $slot_where = ['archives_field'=>'slot'];
        $slot['price'] = Db::name('mill_order_archives_add_price')->where($slot_where)->where(['order_id'=>$order_id])->value('price');
        if(empty($slot['price']))$slot['price'] = Db::name('mill_order_archives_add_price')->where($slot_where)->value('price');
        $slot['sum_price'] = round(($slot['row_area']*$slot['price']),2);
        $sum_price += floatval($slot['sum_price']);
        $table_data[] = ['','','','','','合计开槽(M)','',$slot['row_area'],'','','',$slot['price'],$slot['sum_price'],];

        //合计焊缝(M)
        $weld['row_area'] = Db::name('mill_order_archives')->where(['order_id'=>$order_id])->sum('weld');
        $weld_where = ['archives_field'=>'weld'];
        $weld['price'] = Db::name('mill_order_archives_add_price')->where($weld_where)->where(['order_id'=>$order_id])->value('price');
        if(empty($weld['price']))$weld['price'] = Db::name('mill_order_archives_add_price')->where($weld_where)->value('price');
        $weld['sum_price'] = round(($weld['row_area']*$weld['price']),2);
        $sum_price += floatval($weld['sum_price']);
        $table_data[] = ['','','','','','合计焊缝(M)','',$weld['row_area'],'','','',$weld['price'],$weld['sum_price'],];

        //合计总金额
        $table_data[] = ["[14:1]
                <div style='text-align: right'>合计数量：<a style='font-size: 25px;'>".$sum_number."</a>  合计面积(M²)：<a style='font-size: 25px;'>".$sum_area."</a>  开槽长度：<a id='sum_group_slot' style='font-size: 25px;'>".$slot['row_area']."</a>  焊缝长度：<a id='sum_group_weld' style='font-size: 25px;'>".$weld['row_area']."</a> 合计金额(元)：<a id='sum_group_price' style='font-size: 25px;'>".$sum_price."</a></div>"];

        $js = '<script type="text/javascript">
                $(function() {
                    
                })
            </script>';

        // 批量添加表单项
        $formItems = [];

        //$formItems[] = ['number:4', 'ingots_price_old', '铝锭价', '', $order['ingots_price_old']];
        //$formItems[] = ['number:4', 'ingots_price', '约定铝锭价', '', $order['ingots_price']];
        //$formItems[] = ['text:4', 'ingots_time', '约定铝锭日期', '', $order['ingots_time']];
        //$formItems[] = ['text:6', 'ingots_price_float', '铝锭价浮动值', '', $order['ingots_price_float']];
        //$formItems[] = ['text:6', 'ingots_price_float_price', '铝锭价浮动金额', '', $order['ingots_price_float_price']];

        $formItems[] = ['complexTable:12', 'list_archives_group', '', $table_data, $table_head];

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addFormItems($formItems)// 批量添加表单项
            ->setExtraJs($js)
            ->fetch();
    }

    /**
     * 工程-板厚基价设置列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function orderBasicPriceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['o.archives_status','=',2];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,count(DISTINCT o.id) as order_sum,sum(a.number) as number_sum,sum(a.row_area) as area_sum,o.id as ip_id')
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->where($map)
            ->group('o.order_pid')
            ->order('o.archives_status_time desc,o.order_pid desc')
            ->paginate();

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('工程基价设置') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'a.archives_sn', '档案号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['order_sum', '批次数量'],
                ['number_sum', '产品总量'],
                ['area_sum', '总面积'],
                ['initial_price_p_status','状态','callback',function($value, $data){
                    //$value = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$value])->value('id');
                    //$value = empty($value)?0:1;
                    //$str = FinanceModel::$initial_price_status[$value];
                    $status = OrderModel::status_tag($value,FinanceModel::$initial_price_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['initial_price_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('BasicPrice',['title' => '基价','href' => url('mill/finance/archivesBasicPrice',['order_pid' => '__order_pid__']),'class'=>'btn btn-default','icon'=>''])
            ->addRightButton('addPrice',['title' => '加价','href' => url('mill/finance/archivesAddPriceList',['order_pid' => '__order_pid__']),'class'=>'btn btn-default','icon'=>''])
            ->addRightButton('BasicPriceList',['title' => '所有批次','href' => url('mill/finance/archivesBasicPriceList',['order_pid' => '__order_pid__']),'class'=>'btn btn-default','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 批次-板厚基价设置列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesBasicPriceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['o.archives_status','=',2];
        $order_pid = input('order_pid');
        if(!empty($order_pid))$map[] = ['o.order_pid','=',$order_pid];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,sum(a.number) as number_sum,sum(a.one_area*a.number) as area_sum,o.id as ip_id')
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->where($map)
            ->group('o.id')
            ->order('o.archives_status_time desc,o.id desc')
            ->paginate();

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('工程基价设置') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'a.archives_sn', '档案号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum', '产品总量'],
                ['area_sum', '总面积'],
                ['initial_price_status','状态','callback',function($value, $data){
                    //$value = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$value])->value('id');
                    //$value = empty($value)?0:1;
                    //$str = FinanceModel::$initial_price_status[$value];
                    $status = OrderModel::status_tag($value,FinanceModel::$initial_price_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['initial_price_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('BasicPrice',['title' => '基价','href' => url('mill/finance/archivesBasicPrice',['order_id' => '__id__']),'class'=>'btn btn-default','icon'=>''])
            ->addRightButton('addPrice',['title' => '加价','href' => url('mill/finance/archivesAddPriceList',['order_id' => '__id__']),'class'=>'btn btn-default','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 工程-板厚基价设置列表
     * @return mixed
     */
    public function archivesBasicPrice()
    {

        $order_pid = input('order_pid');
        $order_id = input('order_id');
        if($order_pid){
            //工程计价
            $order = Db::name('mill_order')->where(['order_pid'=>$order_pid])->find();
            $order['id'] = 0;
            $order['archives_sn'] = '';
            $ingots_setting = !empty($order['ingots_setting'])?json_decode($order['ingots_setting'],true):[];

            $order['ingots_price_old'] = !empty($ingots_setting['ingots_price_old'])?$ingots_setting['ingots_price_old']:0;
            $order['ingots_price'] = !empty($ingots_setting['ingots_price'])?$ingots_setting['ingots_price']:0;
            $order['ingots_time'] = !empty($ingots_setting['ingots_time'])?$ingots_setting['ingots_time']:0;
            $order['ingots_price_float'] = !empty($ingots_setting['ingots_price_float'])?$ingots_setting['ingots_price_float']:0;

        }
        else{
            //批次计价
            $order = Db::name('mill_order')->where(['id'=>$order_id])->find();

        }

        if(!empty($order['ingots_time']))$order['ingots_time'] = date('Y-m-d',$order['ingots_time']);

        //基价类型
        $archives_field = Db::name('mill_order_archives_add_price_type')->where(['archives_field'=>'thickness'])->find();

        if ($this->request->isPost()) {
            $data = $this->request->post();

            $validate = [
                'val'               =>  '请填写板厚',
                'basic_price'       =>  '请填写基础单价',
                'float_price'       =>  '请填写铝锭价浮动价格',
            ];
            $goods = MaterialModel::serialize($data['goods'],0,$validate);
            unset($data['goods']);

            //更新定价
            if(!empty($goods)){
                $ids = '';
                foreach ($goods as $pav){
                    $pav_id = $pav['id'];
                    unset($pav['id']);

                    //分类信息
                    $pav['archives_field'] = $archives_field['archives_field'];
                    $pav['type_id'] = $archives_field['id'];
                    //工程信息
                    $pav['title'] = $pav['val'];
                    $pav['order_id'] = $order['id'];
                    $pav['order_pid'] = $order['order_pid'];
                    $pav['archives_sn'] = $order['archives_sn'];

                    if(empty($pav_id))$pav_id = Db::name('mill_order_archives_add_price')->insertGetId($pav);
                    else Db::name('mill_order_archives_add_price')->where('id='.$pav_id)->update($pav);

                    $ids .= ",{$pav_id}";
                }
                $ids = trim($ids,',');

                //删除取消的基价设置
                $where = [
                    ['order_id','=',$order['id']],
                    ['order_pid','=',$order['order_pid']],
                    ['archives_field','=',$archives_field['archives_field']],
                    ['id','not in',$ids],
                ];
                Db::name('mill_order_archives_add_price')->where($where)->delete();
                //更新计价状态
                if(!empty($data['ingots_time'] ))$data['ingots_time'] = strtotime($data['ingots_time'] );
                if(!empty($order['id'])){
                    //批次计价
                    $data['initial_price_status'] = 2;
                    Db::name('mill_order')->where(['id'=>$order['id']])->update($data);
                }
                else {
                    //工程计价
                    $data['initial_price_p_status'] = 2;

                    $data['ingots_setting'] = [
                        'ingots_price_old'          =>  $data['ingots_price_old'],
                        'ingots_price'              =>  $data['ingots_price'],
                        'ingots_time'               =>  $data['ingots_time'],
                        'ingots_price_float'        =>  $data['ingots_price_float'],
                    ];
                    $data['ingots_setting'] = json_encode($data['ingots_setting']);

                    unset($data['ingots_price_old']);
                    unset($data['ingots_price']);
                    unset($data['ingots_time']);
                    unset($data['ingots_price_float']);

                    Db::name('mill_order')->where(['order_pid'=>$order['order_pid']])->update($data);
                }

                //更新工程，或者批次的面积表计价
                FinanceModel::updateOrderAddPrice($order['id'],$order['order_pid']);

            }

            $this->success('编辑成功', cookie('__forward__'));
        }

        //---------------------------------------------工程表单项 start------------------------------------------
        $table_head = [];
        $table_data = [];

        //新增
        $btn_html = "<a style='float: right;' class='btn btn-success' onclick=\"goods_add()\" ><i class='fa fa-plus-circle'></i></a>";

        $table_data[] = [
            "<div style='text-align: center;'>板厚</div>",
            "<div style='text-align: center;'>基础单价</div>",
            "<div style='text-align: center;'>铝锭价浮动价格</div>",
            "<div style='text-align: center;'>加价</div>",
            "<div style='text-align: center;'>铝板单价</div>",
            "<div id='goods_note'><div style='text-align: center;float: left;margin: 7px auto;'></div>".$btn_html."</div>",
        ];

        $price_list = Db::name('mill_order_archives_add_price')->where(['archives_field'=>$archives_field['archives_field'],'order_id'=>$order['id'],'order_pid'=>$order['order_pid']])->select();
        if(empty($price_list)){
            $price_list[] = [
                'id'                    =>  '',
                'val'                   =>  '2.0',
                'basic_price'           =>  '',
                'float_price'           =>  '',
                'float_add_price'       =>  '',
                'price'                 =>  '',
            ];
        }
        foreach ($price_list as $sak=>$sav){
            $table_data[] = [
                "[0:1]
                    <input class='form-control goods' type='hidden' name='goods[id][]' value='{$sav['id']}'>
                    <input class='form-control goods' type='number' name='goods[val][]' value='{$sav['val']}'>
                    ",
                "[0:1]
                    <input class='form-control goods price basic_price' type='number' name='goods[basic_price][]' value='{$sav['basic_price']}'>
                    ",
                "[0:1]
                    <input class='form-control goods price float_price' type='number' name='goods[float_price][]' value='{$sav['float_price']}'>
                    ",
                "[0:1]
                    <input class='form-control goods float_add_price' type='number' name='goods[float_add_price][]' value='{$sav['float_add_price']}'>
                    ",
                "[0:1]
                    <input class='form-control goods sum_price' type='number' name='goods[price][]' value='{$sav['price']}'>
                    ",
                "[0:1]
                    <a class='btn btn-danger goods goods_del' onclick=\"goods_del(this)\" ><i class='fa fa-times'></i></a>
                    ",
            ];


        }

        //单价设置
        $title = "{$order['engineering']} 基价设置";

        $js = '<script type="text/javascript">
                $(function() {
                    
                    //监听铝锭价日期设置
                    $(document).on("input propertychange","#ingots_price,#ingots_price_old,#ingots_price_float", function() {
                        sum_price();
                    });
                    //监听铝锭价日期设置
                    $(document).on("input propertychange",".price", function() {
                        sum_price();
                    });
                });
                //重新计算基价
                function sum_price() {
                    
                    
                    //浮动系数(向下取整) = （下单日铝锭价 - 合同铝锭价）/ 铝锭浮动值
                    var float_xs = 0;
                    
                    var price = $("#ingots_price").val();//合同铝锭价
                    var price_old = $("#ingots_price_old").val();//下单日铝锭价
                    var float = $("#ingots_price_float").val();//铝锭浮动值
                    
                    //浮动系数(向下取整) = （下单日铝锭价 - 合同铝锭价）/ 铝锭浮动值
                    if(float != 0)float_xs = parseInt((price - price_old)/float);//向下取整
                    
                    //遍历基价设置
                    $(".float_price").each(function(i,j){
                        var basic_price = $(j).parents("tr").find(".basic_price").val();//下单日铝锭价
                        var float_add_price = parseFloat($(j).val()) * parseFloat(float_xs);
                        var sum_price = parseFloat(basic_price) + parseFloat(float_add_price);
                        $(j).parents("tr").find(".float_add_price").val(float_add_price);//下单日铝锭价
                        $(j).parents("tr").find(".sum_price").val(sum_price);//下单日铝锭价
                        
                    })
                }
                //删除
                function goods_del(obj) {
                    var length = $(".goods_del").parent("td").parent("tr").length;
                    
                    if(length == 1){
                        return false;
                    }
                    $(obj).parent().parent().remove();
                }
                //新增
                function goods_add(obj) {
                    var add = $(".goods").parent().parent().html();
                    add = "<tr class=\'hidden\'>"+add+"</tr>";
                    $(add).insertAfter($(".goods").parent("td").parent("tr:last"));
                    $(".goods").parent("td").parent("tr:last").find("input[name=\'goods[id][]\']").val("");
                    $(".goods").parent("td").parent("tr:last").find(".goods").val("");
                    $(".goods").parent("td").parent("tr:last").removeClass("hidden");
                    
                }
            </script>';

        // 批量添加表单项
        $formItems = [];

        $formItems[] = ['number:6', 'ingots_price_old', '合同铝锭价', '', $order['ingots_price_old']];
        $formItems[] = ['static:6', 'ingots_price_old1', "."];
        $formItems[] = ['number:6', 'ingots_price', '下单日铝锭价', '', $order['ingots_price']];
        $formItems[] = ['date:6', 'ingots_time', '下单日期', '', $order['ingots_time']];
        $formItems[] = ['text:6', 'ingots_price_float', '铝锭浮动值', '', $order['ingots_price_float']];

        $formItems[] = ['complexTable:12', 'list_archives_group', '', $table_data, $table_head];

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addFormItems($formItems)// 批量添加表单项
            ->setExtraJs($js)
            ->fetch();
    }
    /**
     * 工程-板型加价设置列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesPlatePriceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['o.archives_status','=',2];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,sum(a.number) as number_sum,sum(a.one_area*a.number) as area_sum,o.id as ip_id')
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->where($map)
            ->group('o.id')
            ->order('o.archives_status_time desc,o.id desc')
            ->paginate();

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('工程板型加价设置') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'a.archives_sn', '档案号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum', '产品总量'],
                ['area_sum', '总面积'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('archivesPrice',['title' => '设置','href' => url('mill/finance/archivesPlatePrice',['order_id' => '__id__']),'class'=>'btn btn-default','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 工程-板型加价设置列表
     * @return mixed
     */
    public function archivesPlatePrice()
    {

        if(empty($order_id))$order_id = input('order_id');//指定工程

        $order = Db::name('mill_order')->where(['id'=>$order_id])->find();

        if ($this->request->isPost()) {
            $data = $this->request->post();

            $validate = [
                'price'       =>  '请填写加价',
            ];
            $goods = MaterialModel::serialize($data['goods'],0,$validate);
            unset($data['goods']);

            //更新定价
            if(!empty($goods)){

                foreach ($goods as $pav){

                    $pav_id_old = $pav_id = $pav['id'];
                    unset($pav['id']);

                    $price_show = Db::name('mill_order_archives_add_price')->where(['id'=>$pav_id])->find();

                    if(empty($price_show['order_id'])){
                        $price_show['price'] = $pav['price'];
                        $price_show['order_id'] = $order['id'];
                        $price_show['order_pid'] = $order['order_pid'];
                        $price_show['archives_sn'] = $order['archives_sn'];
                        $price_show['pid'] = $pav_id_old;

                        $pav_id = '';
                    }

                    if(empty($pav_id))$pav_id = Db::name('mill_order_archives_add_price')->insertGetId($pav);
                    else Db::name('mill_order_archives_add_price')->where('id='.$pav_id)->update($pav);

                    //替换成自定义的加价ID
                    FinanceModel::updateArchivesAddPriceIds($pav_id_old,$pav_id,$order);
                }


            }

            $this->success('编辑成功', cookie('__forward__'));
        }

        //---------------------------------------------工程表单项 start------------------------------------------
        $table_head = [];
        $table_data = [];

        $table_data[] = [
            "<div style='text-align: center;'>类型</div>",
            "<div style='text-align: center;'>指定值</div>",
            "<div style='text-align: center;'>范围</div>",
            "<div style='text-align: center;'>加价</div>",
        ];

        $add_price_ids = Db::name('mill_order_archives')
            ->where(['order_id'=>$order['id']])
            ->value('group_concat(DISTINCT add_price_ids) as add_price_ids');
        $add_price_ids = array_unique(explode(',',$add_price_ids));
        $add_price_ids = implode(',',$add_price_ids);

        if(!empty($add_price_ids)){
            $where = [
                ['t.type','in','3,4'],
                ['p.id','in',$add_price_ids],
            ];
            $price_list = Db::name('mill_order_archives_add_price')
                ->alias('p')
                ->field('p.*,t.type_title')
                ->leftJoin('mill_order_archives_add_price_type t','t.id=p.type_id')
                ->where($where)
                ->select();

            foreach ($price_list as $sak=>$sav){

                $sav['min_val_html'] = '';
                if(!empty($sav['min_val']))$sav['min_val_html'] .= $sav['min_val'];
                if(!empty($sav['max_val']))$sav['min_val_html'] .= "<span class='input-group-addon' style='display: inline;padding: 7px 7px 6px 7px;'> — </span>".$sav['max_val'];
                $table_data[] = [
                    "[0:1]
                    {$sav['type_title']} {$sav['title']}
                    ",
                    "[0:1]
                    {$sav['val']}
                    ",
                    "[0:1]
                    {$sav['min_val_html']}
                    ",
                    "[0:1]
                    <input class='form-control goods' type='hidden' name='goods[id][]' value='{$sav['id']}'>
                    <input class='form-control goods' type='number' name='goods[price][]' value='{$sav['price']}'>
                    ",
                ];


            }
        }


        //单价设置
        $title = "{$order['engineering']} 板型加价设置";

        $js = '<script type="text/javascript">
                $(function() {
                    
                    //监听铝锭价日期设置
                    $(document).on("input propertychange","#ingots_price,#ingots_price_old,#ingots_price_float", function() {
                        sum_price();
                    });
                    //监听铝锭价日期设置
                    $(document).on("input propertychange",".price", function() {
                        sum_price();
                    });
                });
                //重新计算基价
                function sum_price() {
                    
                    
                    //浮动系数(向下取整) = （下单日铝锭价 - 合同铝锭价）/ 铝锭浮动值
                    var float_xs = 0;
                    
                    var price = $("#ingots_price").val();//合同铝锭价
                    var price_old = $("#ingots_price_old").val();//下单日铝锭价
                    var float = $("#ingots_price_float").val();//铝锭浮动值
                    
                    //浮动系数(向下取整) = （下单日铝锭价 - 合同铝锭价）/ 铝锭浮动值
                    if(float != 0)float_xs = parseInt((price - price_old)/float);//向下取整
                    
                    //遍历基价设置
                    $(".float_price").each(function(i,j){
                        var basic_price = $(j).parents("tr").find(".basic_price").val();//下单日铝锭价
                        var float_add_price = parseFloat($(j).val()) * parseFloat(float_xs);
                        var sum_price = parseFloat(basic_price) + parseFloat(float_add_price);
                        $(j).parents("tr").find(".float_add_price").val(float_add_price);//下单日铝锭价
                        $(j).parents("tr").find(".sum_price").val(sum_price);//下单日铝锭价
                        
                    })
                }
                //删除
                function goods_del(obj) {
                    var length = $(".goods_del").parent("td").parent("tr").length;
                    
                    if(length == 1){
                        return false;
                    }
                    $(obj).parent().parent().remove();
                }
                //新增
                function goods_add(obj) {
                    var add = $(".goods").parent().parent().html();
                    add = "<tr class=\'hidden\'>"+add+"</tr>";
                    $(add).insertAfter($(".goods").parent("td").parent("tr:last"));
                    $(".goods").parent("td").parent("tr:last").find("input[name=\'goods[id][]\']").val("");
                    $(".goods").parent("td").parent("tr:last").find(".goods").val("");
                    $(".goods").parent("td").parent("tr:last").removeClass("hidden");
                    
                }
            </script>';

        // 批量添加表单项
        $formItems = [];

        $formItems[] = ['complexTable:12', 'list_archives_group', '', $table_data, $table_head];

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addFormItems($formItems)// 批量添加表单项
            ->setExtraJs($js)
            ->fetch();
    }
    /**
     * 工程-颜色加价设置列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesColorPriceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['o.archives_status','=',2];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,sum(a.number) as number_sum,sum(a.one_area*a.number) as area_sum,o.id as ip_id')
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->where($map)
            ->group('o.id')
            ->order('o.archives_status_time desc,o.id desc')
            ->paginate();

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('工程板型加价设置') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'a.archives_sn', '档案号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum', '产品总量'],
                ['area_sum', '总面积'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('archivesPrice',['title' => '设置','href' => url('mill/finance/archivesColorPrice',['order_id' => '__id__']),'class'=>'btn btn-default','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 工程-颜色加价设置列表
     * @return mixed
     */
    public function archivesColorPrice()
    {

        if(empty($order_id))$order_id = input('order_id');//指定工程

        $order = Db::name('mill_order')->where(['id'=>$order_id])->find();

        if ($this->request->isPost()) {
            $data = $this->request->post();

            $validate = [
                'price'       =>  '请填写加价',
            ];
            $goods = MaterialModel::serialize($data['goods'],0,$validate);
            unset($data['goods']);

            //更新定价
            if(!empty($goods)){

                foreach ($goods as $pav){

                    $pav_id_old = $pav_id = $pav['id'];
                    unset($pav['id']);

                    $price_show = Db::name('mill_order_archives_add_price')->where(['id'=>$pav_id])->find();

                    if(empty($price_show['order_id'])){
                        $price_show['price'] = $pav['price'];
                        $price_show['price'] = $pav['price'];
                        $price_show['order_id'] = $order['id'];
                        $price_show['order_pid'] = $order['order_pid'];
                        $price_show['pid'] = $pav_id_old;

                        $pav_id = '';
                    }

                    if(empty($pav_id))$pav_id = Db::name('mill_order_archives_add_price')->insertGetId($pav);
                    else Db::name('mill_order_archives_add_price')->where('id='.$pav_id)->update($pav);

                    //替换成自定义的加价ID
                    FinanceModel::updateArchivesAddPriceIds($pav_id_old,$pav_id,$order);
                }


            }

            $this->success('编辑成功', cookie('__forward__'));
        }

        //---------------------------------------------工程表单项 start------------------------------------------
        $table_head = [];
        $table_data = [];

        $table_data[] = [
            "<div style='text-align: center;'>类型</div>",
            "<div style='text-align: center;'>色号</div>",
            "<div style='text-align: center;'>加价</div>",
        ];

        $add_price_ids = Db::name('mill_order_archives')
            ->where(['order_id'=>$order['id']])
            ->value('group_concat(DISTINCT add_price_ids) as add_price_ids');
        $add_price_ids = array_unique(explode(',',$add_price_ids));
        $add_price_ids = implode(',',$add_price_ids);

        if(!empty($add_price_ids)){
            $where = [
                ['t.type','in','1'],
                ['p.id','in',$add_price_ids],
            ];
            $price_list = Db::name('mill_order_archives_add_price')
                ->alias('p')
                ->field('p.*,t.type_title')
                ->leftJoin('mill_order_archives_add_price_type t','t.id=p.type_id')
                ->where($where)
                ->select();

            foreach ($price_list as $sak=>$sav){

                $table_data[] = [
                    "[0:1]
                    {$sav['type_title']} {$sav['title']}
                    ",
                    "[0:1]
                    {$sav['val']}
                    ",
                    "[0:1]
                    <input class='form-control goods' type='hidden' name='goods[id][]' value='{$sav['id']}'>
                    <input class='form-control goods' type='number' name='goods[price][]' value='{$sav['price']}'>
                    ",
                ];


            }
        }


        //单价设置
        $title = "{$order['engineering']} 色号加价设置";

        $js = '<script type="text/javascript">
                $(function() {
                    
                    //监听铝锭价日期设置
                    $(document).on("input propertychange","#ingots_price,#ingots_price_old,#ingots_price_float", function() {
                        sum_price();
                    });
                    //监听铝锭价日期设置
                    $(document).on("input propertychange",".price", function() {
                        sum_price();
                    });
                });
                //重新计算基价
                function sum_price() {
                    
                    
                    //浮动系数(向下取整) = （下单日铝锭价 - 合同铝锭价）/ 铝锭浮动值
                    var float_xs = 0;
                    
                    var price = $("#ingots_price").val();//合同铝锭价
                    var price_old = $("#ingots_price_old").val();//下单日铝锭价
                    var float = $("#ingots_price_float").val();//铝锭浮动值
                    
                    //浮动系数(向下取整) = （下单日铝锭价 - 合同铝锭价）/ 铝锭浮动值
                    if(float != 0)float_xs = parseInt((price - price_old)/float);//向下取整
                    
                    //遍历基价设置
                    $(".float_price").each(function(i,j){
                        var basic_price = $(j).parents("tr").find(".basic_price").val();//下单日铝锭价
                        var float_add_price = parseFloat($(j).val()) * parseFloat(float_xs);
                        var sum_price = parseFloat(basic_price) + parseFloat(float_add_price);
                        $(j).parents("tr").find(".float_add_price").val(float_add_price);//下单日铝锭价
                        $(j).parents("tr").find(".sum_price").val(sum_price);//下单日铝锭价
                        
                    })
                }
                //删除
                function goods_del(obj) {
                    var length = $(".goods_del").parent("td").parent("tr").length;
                    
                    if(length == 1){
                        return false;
                    }
                    $(obj).parent().parent().remove();
                }
                //新增
                function goods_add(obj) {
                    var add = $(".goods").parent().parent().html();
                    add = "<tr class=\'hidden\'>"+add+"</tr>";
                    $(add).insertAfter($(".goods").parent("td").parent("tr:last"));
                    $(".goods").parent("td").parent("tr:last").find("input[name=\'goods[id][]\']").val("");
                    $(".goods").parent("td").parent("tr:last").find(".goods").val("");
                    $(".goods").parent("td").parent("tr:last").removeClass("hidden");
                    
                }
            </script>';

        // 批量添加表单项
        $formItems = [];

        $formItems[] = ['complexTable:12', 'list_archives_group', '', $table_data, $table_head];

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addFormItems($formItems)// 批量添加表单项
            ->setExtraJs($js)
            ->fetch();
    }

    /**
     * 审核面积表初始价格
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesPriceExamine()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['o.initial_price_status','=',1];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,sum(a.number) as number_sum,sum(a.one_area*a.number) as area_sum,o.id as ip_id')
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->where($map)
            ->group('o.id')
            ->order('o.archives_status_time desc,o.id desc')
            ->paginate();

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('面积表计价') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'a.archives_sn', '档案号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum', '产品总量'],
                ['area_sum', '总面积'],
                ['initial_price_status','计价状态','callback',function($value, $data){
                    //$value = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$value])->value('id');
                    //$value = empty($value)?0:1;
                    //$str = FinanceModel::$initial_price_status[$value];
                    $status = OrderModel::status_tag($value,FinanceModel::$initial_price_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['initial_price_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('archivesPrice',['title' => '详情','href' => url('mill/finance/archivesPrice',['order_id' => '__id__']),'class'=>'btn btn-default','icon'=>''])
            ->addRightButton('backEnable',['title' => '审核通过','href' => url('archivesPriceEnable',['id' => '__id__']).'?fieldv=initial_price_status|2','class'=>'btn btn-default ajax-get','icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('archivesPriceDisable',['id' => '__id__','field'=>'initial_price_status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 面积表初始价格审核
     */
    public function archivesPriceEnable()
    {
        $id = input('param.id');
        $fieldv = input('param.fieldv');
        $fieldv = explode('|',$fieldv);
        if(false === OrderModel::where('id', $id)->setField($fieldv[0], $fieldv[1]))$this->error('审核失败，工程ID：'.$id);
        //审核人员
        OrderModel::where('id', $id)->setField($fieldv[0].'_verify_uid', UID);
        //审核时间
        OrderModel::where('id', $id)->setField($fieldv[0].'_time', time());


        $order = Db::name('mill_order')->where(['id'=>$id])->find();
        $order['company'] = Db::name('mill_client')->where(['id'=>$order['client_id']])->value('company');
        //更新调账单
        $finance = Db::name('mill_finance')->where(['order_pid'=>$order['order_pid'],'pid'=>0])->find();
        if(empty($finance)){
            //工程总金额
            $order_sum_money = FinanceModel::orderSumMoney($order['order_pid']);
            //获取收款信息
            $finance_config = Db::name('mill_order_contract')->where(['order_id'=>$order['order_pid']])->find();
            $finance_type = $finance_config['finance_type'];//收款方式
            $finance_money = $finance_config['finance_money'];//定金
            $late_money = $finance_config['late_money'];//滞纳金
            $late_time = strtotime($finance_config['late_time']);//滞纳金归还时间

            $finance_add = [
                'create_time'           =>  time(),
                'update_time'           =>  time(),
                'order_pid'             =>  $order['order_pid'],
                'order_sn'              =>  $order['order_sn'],
                'engineering'           =>  $order['engineering'],
                'company'               =>  $order['company'],
                'handle'                =>  $order['archives_handle'],
                //收款
                'sum_money'             =>  $order_sum_money,//工程总金额
                'deposit_money'         =>  $finance_money,//定金
                'late_money'            =>  $late_money,//滞纳金
                'late_time'             =>  $late_time,//滞纳金归还时间
            ];
            $finance['id'] = Db::name('mill_finance')->insertGetId($finance_add);

        }
        $order_sum_money = $order['initial_price'] - $order['old_initial_price'];
        Db::name('mill_finance')->where(['id'=>$finance['id']])->setInc('sum_money',$order_sum_money);
        Db::name('mill_order')->where(['id'=>$order['id']])->update(['old_initial_price'=>$order['initial_price']]);

        //推送消息
        $status_str = '审核';
        $content = "工程编号<span class='text-primary'>[{$order['archives_sn']}]</span>{$status_str}通过";
        $href = admin_url('archivespricelist')."?_s=a.archives_sn={$order['archives_sn']}&_o=a.archives_sn=like";
        //LogModel::send_message("面积表计价{$status_str}",$content,$href);

        $this->success('提交成功', null, '_parent_reload');

    }
    /**
     * 面积表初始价格审核不通过
     */
    public function archivesPriceDisable()
    {
        $action = new Order();
        return $action->notDisable();
    }


    /**
     * 面积表加价设置列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesAddPriceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['p.status','=',1];
        $map[] = ['t.type','<>',2];
        $order_pid = input('order_pid');
        $order_id = input('order_id');
        if(!empty($order_pid))$map[] = ['order_pid','=',$order_pid];
        if(!empty($order_id))$map[] = ['order_id','=',$order_id];
        // 数据列表
        $data_list = Db::name('mill_order_archives_add_price')
            ->alias('p')
            ->field('p.*,t.type_title')
            ->leftJoin('mill_order_archives_add_price_type t','t.id=p.type_id')
            ->where($map)
            ->order('t.type asc,t.type_title asc,p.title asc,val asc,min_val asc')
            ->select();

        if(!empty($data_list)){
            foreach ($data_list as &$v){

                //条件说明
                $v['equa_str'] = FinanceModel::archivesAddPriceText($v['id']);
            }
        }

        $type_list = ClientModel::getAddPriceTypeList();
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('加价设置') // 页面标题
            ->setTableName('mill_order_archives_add_price') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['select:2', 'p.type_id', '类型','','',$type_list],
                ['text:2', 'p.title', '名称', 'like'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['type_title', '类型'],
                ['title', '名称'],
                ['equa_str', '条件'],
                ['price', '加价'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('add',['title' => '新增','href' => url('archivesAddPrice',['order_pid'=>$order_pid,'order_id'=>$order_id]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['90%', '90%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('edit',['title' => '编辑','href' => url('archivesAddPrice',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['90%', '90%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'equa_str'  => 350,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 面积表加价设置
     * @return mixed
     */
    public function archivesAddPrice()
    {

        $id = input('id');
        $order_pid = input('order_pid');//指定工程
        $order_id = input('order_id');//指定批次

        if ($this->request->isPost()) {
            $data = $this->request->post();

            if(empty($data['type_id']))$this->error('请选择类型');
            if(empty($data['title']))$this->error('请填写名称');
            if(empty($data['price']))$this->error('请填写价格');

            $type_show = Db::name('mill_order_archives_add_price_type')->where(['id'=>$data['type_id']])->find();

            if($type_show['equa_type'] != 0 && empty($data['min_val']))$this->error('请填写范围');

            $data['archives_field'] = $type_show['archives_field'];

            if($id)Db::name('mill_order_archives_add_price')->where(['id'=>$id])->update($data);
            else {
                if(!empty($order_pid))$data['order_pid'] = $order_pid;
                if(!empty($order_id))$data['order_id'] = $order_id;
                Db::name('mill_order_archives_add_price')->insert($data);
            }

            //更新工程，或者批次的面积表计价
            FinanceModel::updateOrderAddPrice($order_id,$order_pid);

            $this->success('操作成功','', '_parent_reload');
        }

        $info = [];
        if(!empty($id))$info = Db::name('mill_order_archives_add_price')->where(['id'=>$id])->find();

        $table_head[] = [
            "<div style='text-align: center;'>类型</div>",
            "<div style='text-align: center;'>名称</div>",
            "<div style='text-align: center;'>指定值</div>",
            "<div style='text-align: center;'>范围</div>",
            "<div style='text-align: center;'>加价</div>",
        ];

        $type_list = Db::name('mill_order_archives_add_price_type')->where('status=1')->order('type asc,type_title asc')->select();
        $type_list_new = [];
        $type_list_arr = [];
        foreach ($type_list as $k=>$v){
            $type_list_new[$v['id']] = $v;
            $type_list_arr[$v['id']] = $v['type_title'];
        }

        $readonly1 = "readonly1";
        $readonly2 = "readonly2";

        if(empty($info['min_val']))$readonly2 .= ' readonly';
        else $readonly1 .= ' readonly';

        $table_data[] = [
            "[0:1]
            ".MaterialModel::inputToText('type_id',isset($info['type_id'])?$info['type_id']:'','','','select','not-js-select',$type_list_arr),
            "[0:1]
            ".MaterialModel::inputToText('title',isset($info['title'])?$info['title']:'','','','input',""),
            "[0:1]
            ".MaterialModel::inputToText('val',isset($info['val'])?$info['val']:'','','','input',"{$readonly1}"),
            "[0:1]
            ".MaterialModel::inputToText('min_val',isset($info['min_val'])?$info['min_val']:'','','width: 40%;display: inline;','input',"{$readonly2}").
            "<span class='input-group-addon' style='display: inline;padding: 7px 7px 6px 7px;'> — </span>
            ".MaterialModel::inputToText('max_val',isset($info['max_val'])?$info['max_val']:'','','width: 40%;display: inline;','input',"{$readonly2}"),
            "[0:1]
            ".MaterialModel::inputToText('price',isset($info['price'])?$info['price']:'','','','input',""),
        ];

        $js = '<script type="text/javascript">
                var type_list = \''.json_encode($type_list_new).'\';
                type_list = $.parseJSON(type_list);
                $(function() {
                
                    //名称事件
                    $("body").on("change","select[name=\'type_id\']",function(){
                        var tr_obj = $(this).parents("tr");
                        var type_id = tr_obj.find("select[name=\'type_id\']").val();
                        var type_show = type_list[type_id];
                        
                        if(type_show){
                            
                            //equa_type(计价类型) 0:常规计价 1:按大于小于方式计价
                            if(type_show.equa_type == 0){
                                tr_obj.find(".readonly1").prop("readonly", false);
                                tr_obj.find(".readonly1").removeClass("readonly");
                                
                                tr_obj.find(".readonly2").prop("readonly", true);
                                tr_obj.find(".readonly2").addClass("readonly");
                                tr_obj.find(".readonly2").val("");
                            }
                            else{
                                tr_obj.find(".readonly2").prop("readonly", false);
                                tr_obj.find(".readonly2").removeClass("readonly");
                                
                                tr_obj.find(".readonly1").prop("readonly", true);
                                tr_obj.find(".readonly1").addClass("readonly");
                                tr_obj.find(".readonly1").val("");
                            }
                        }
                        
                        
                    });
                });
            </script>';

        return ZBuilder::make('form')
            ->setPageTitle('加价设置') // 页面标题
            ->addFormItems([
                ['complexTable:12', 'list_archives_group', '', $table_data, $table_head]
            ])// 批量添加表单项
            ->setExtraJs($js)
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 设定面积表初始价格
     * @return mixed
     */
    public function archivesAddPrice_old()
    {

        if(empty($order_id))$order_id = input('order_id');//指定工程
        if(empty($order_id))$this->error('错误操作');

        if ($this->request->isPost()) {
            $data = $this->request->post();

            $_give_scale = $data['_give_scale'];
            foreach ($_give_scale as &$sv){
                if(empty($sv))$this->error('请填写完整分配比例');
            }
            $_give_scale = implode("\r\n",$_give_scale);

            //更新定价
            if(!empty($data['price_arr'])){
                foreach ($data['price_arr'] as $pav){
                    $pav_id = $pav['id'];
                    unset($pav['id']);

                    if(empty($pav_id))Db::name('mill_order_archives_initial_price')->insert($pav);
                    else Db::name('mill_order_archives_initial_price')->where('id='.$pav_id)->update($pav);

                    //更新面积表单价
                    $archives_where = ['id'=>$pav['order_id'],'color'=>$pav['color'],'thickness'=>$pav['thickness'],'model'=>$pav['model']];
                    $archives_list = Db::name('mill_order_archives')->where($archives_where)->select();
                    if(!empty($archives_list)){
                        foreach ($archives_list as $av){
                            $archives_price = $pav['price'];
                            Db::name('mill_order_archives')->where(['id'=>$av['id']])->update(['price'=>$archives_price]);
                            //更新扫码记录单价
                            $log_list = Db::name('mill_order_archives_give_log')->where(['archives_id'=>$av['id']])->select();
                            if(!empty($log_list)){
                                foreach ($log_list as $lv){
                                    $lv_price = $archives_price * ($lv['scale']/100);
                                    Db::name('mill_order_archives_give_log')->where(['id'=>$lv['id']])->update(['archives_price'=>$lv_price,'price'=>$lv_price]);
                                }
                            }
                        }
                    }

                }

                //更新计价状态
                Db::name('mill_order')->where(['id'=>$pav['order_id']])->update(['initial_price_status'=>1,'initial_price'=>$data['sum_group_price'],'give_scale'=>$_give_scale]);

            }

            ////自动更新合同收款方式
            //$contract_add = [
            //    'finance_type'          =>  $data['finance_type'],
            //    'finance_money'         =>  $data['finance_money'],
            //    'late_money'            =>  $data['late_money'],
            //    'late_time'             =>  $data['late_time'],
            //    'finance_config'        =>  json_encode($data['finance_config'],JSON_UNESCAPED_UNICODE),
            //    'status'                =>  3,
            //    'update_time'           =>  time(),
            //];

            //if(!empty($contract)){
            //    $contract_add['id'] = $contract['id'];
            //    ContractModel::update($contract_add);
            //}
            //else {
            //
            //    $contract_add['contract_sn'] = "SWAXC".date('Ymd')."-{$order_id}";
            //
            //    $contract_add['order_id'] = $order_id;
            //    $contract_add['order_pid'] = $order_pid;
            //    $contract_add['create_time'] = time();
            //    $contract_add['create_time'] = time();
            //    ContractModel::create($contract_add);
            //}

            $this->success('编辑成功', cookie('__forward__'));
        }

        $table_arr = FinanceModel::fromArchivesAddPriceTabale($order_id);

        $where[] = ['a.order_id','=',$order_id];

        //单价设置
        $order = $table_arr['order_info'];
        $title = "{$order['engineering']} {$order['archives_sn']} 面积表计价";

        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];
        $js = $table_arr['js'];

        $js .= '<script type="text/javascript">
                $(function() {
                    $("input[name=\'finance_type\']").click(function() {
                        var val = $(this).val();
                        $(".finance").hide();
                        $(".finance").removeClass("hidden");
                        $(".finance[data-type=\'"+val+"\']").show();
                    });
                });
                
                //加价设置，子窗口赋值
                function setAddPriceText(rel){
                    this.rel=rel;
                    //赋值处理
                    add_price_text(rel);
                }
                //加价设置，子窗口获取值
                function add_price_text(rel){
                    var obj = $(".price_show[data-i=\'"+rel._parent_i+"\']");
                    obj.html(rel.text);
                }
            </script>';

        // 批量添加表单项
        $formItems = [];

        $formItems[] = ['complexTable:12', 'list_archives_group', '', $table_data, $table_head];

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addFormItems($formItems)// 批量添加表单项
            ->setExtraJs($js)
            ->fetch();
    }
    /**
     * 加价
     * @return mixed
     */
    public function archivesAddPriceSetting()
    {
        $_parent_i = input('_parent_i');
        $order_id = input('order_id');
        $type = input('type');

        if ($this->request->isPost()) {
            $data = input();

            //要校验的字段
            $validate = [
                'type_id'               =>  '请选择类型',
                //'equa'                  =>  '请选择公式1',
                //'val'                   =>  '请填写值1',
            ];
            $lists = MaterialModel::serialize($data['goods'],0,$validate);
            if(!is_array($lists))$this->error($lists);
            unset($data['goods']);

            $order = Db::name('mill_order')->where(['id'=>$order_id])->find();

            $ids = '';
            foreach ($lists as &$v){

                $v['order_id'] = $order['id'];
                $v['archives_sn'] = $order['archives_sn'];
                if(empty($v['create_time']))$v['create_time'] = time();

                $type_show = Db::name('mill_order_archives_add_price_type')->where(['id'=>$v['type_id']])->find();

                $v['archives_field'] = $type_show['archives_field'];
                $v['title'] = "{$type_show['type_p_title']} {$type_show['type_title']}";
                $v['title'] = trim($v['title']);

                if(!empty($v['id']))Db::name('mill_order_archives_add_price')->where(['id'=>$v['id']])->update($v);
                else $v['id'] = Db::name('mill_order_archives_add_price')->insertGetId($v);
                $ids .= ",{$v['id']}";
            }
            $ids = trim($ids,',');
            //删除被移除的数据
            Db::name('mill_order_archives_add_price')->where([['type','=',$type],['order_id','=',$data['order_id']],['id','not in',$ids]])->delete();

            //$this->success('操作成功','','_parent_reload');

            $text = FinanceModel::archivesAddPriceText($order_id,$type);
            $this->success('操作成功','',$text);
        }

        $where = [
            ['p.order_id','=',$order_id],
            ['t.type','=',$type],
        ];
        $data['lists'] = Db::name('mill_order_archives_add_price')
            ->alias('p')
            ->field('p.*')
            ->leftJoin('mill_order_archives_add_price_type t','t.id=p.type_id')
            ->where($where)
            ->order('t.type_p_title asc,t.type_title asc')
            ->select();

        if(empty($data['lists'])){
            $data['lists'][] = [
                'id'                =>  '',
                'order_id'          =>  $order_id,
                'archives_sn'       =>  '',
                'title'             =>  '',
                'equa'              =>  '',
                'val'               =>  '',
                'type'              =>  '',
                'equa2'             =>  '',
                'val2'              =>  '',
                'note'              =>  '',
                'price'             =>  0,
                'create_time'       =>  time(),
                'type_id'           =>  0,
                'archives_field'    =>  '',
            ];
        }

        $type_list = Db::name('mill_order_archives_add_price_type')->field("*,concat(type_p_title,' ',type_title) as title")->where(['type'=>$type])->order('type_p_title asc,type_title asc')->select();
        $table_list_new = [];
        $table_list_arr = [];
        foreach ($type_list as $k=>$v){
            $table_list_new[$v['id']] = $v;
            $table_list_arr[$v['id']] = $v['title'];
        }

        $data['type_list_arr'] = $table_list_arr;
        $data['equa_arr'] = ['>'=>'>','>='=>'>=','='=>'=','<'=>'<','<='=>'<='];
        $data['type_arr'] = [0=>'无',1=>'且'];

        $table_arr = ContractModel::fromAddPrice($data);
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        $js = '<script type="text/javascript">
                var type_list = \''.json_encode($table_list_new).'\';
                type_list = $.parseJSON(type_list);
                $(function() {
                
                
                    //提交表单，并传值给父窗口
                    $("body").on(\'click\',"button[type=\'submit\']", function(){
                        var msg, self   = jQuery(this);
                        var target_form = self.attr("target-form");
                        var form        = jQuery(\'form[name=\' + target_form + \']\');
                        var ajax_url    = form.attr("action");
                        var form_data   = form.serialize();
                        
                        //Dolphin.pageLoader();
                        self.attr("autocomplete", "off").prop("disabled", true);
                        // 发送ajax请求
                        jQuery.post(ajax_url, form_data, {}, \'json\').success(function(res) {
                            //Dolphin.pageLoader(\'hide\');
                            msg = res.msg;
                            if (res.code) {
                                Dolphin.notify(msg, "success");
                                
                                
                                setTimeout(function () {
                                    //父窗口索引
                                    var _parent_i = \''.$_parent_i.'\';
                                    //传递给父窗口的值
                                    var arr = {
                                        _parent_i:_parent_i,
                                        text:res.data
                                    };
                                    
                                    //子窗口索引
                                    var index = parent.layer.getFrameIndex(window.name);
                                    //向父窗口传值
                                    parent.setAddPriceText(arr);
                                    //关闭子窗口
                                    parent.layer.close(index);
                                }, 1000);
                            } else {
                            
                                Dolphin.notify(msg, "danger");
                            }
                            self.attr("autocomplete", "on").prop("disabled", false);
                        }).fail(function (res) {
                            //Dolphin.pageLoader(\'hide\');
                            Dolphin.notify("服务器内部错误~", "danger");
                            self.attr("autocomplete", "on").prop("disabled", false);
                        });
            
            
                        return false;
                        
                    });
                
                    //名称事件
                    $("body").on("change","select[name=\'goods[type_id][]\']",function(){
                        var tr_obj = $(this).parents("tr");
                        var type_id = tr_obj.find("select[name=\'goods[type_id][]\']").val();
                        var type_show = type_list[type_id];
                        
                        if(type_show){
                            
                            //equa_type(计价类型) 0:常规计价 1:按大于小于方式计价
                            if(type_show.equa_type == 0){
                                //tr_obj.find("select[name=\'goods[equa][]\']").find("option[value=\'=\']").prop("selected",true);
                                //tr_obj.find(".equa").prop("disabled", true);
                                tr_obj.find(".equa").prop("readonly", true);
                                tr_obj.find(".equa").addClass("readonly");
                                tr_obj.find(".equa").val("");
                            }
                            else{
                                //tr_obj.find("select[name=\'goods[equa][]\']").find("option").eq(0).prop("selected",true);
                                tr_obj.find(".equa").prop("readonly", false);
                                tr_obj.find(".equa").removeClass("readonly");
                            }
                        }
                        
                        //var type_pid = tr_obj.find("input[name=\'goods[type_pid][]\']").val();
                        //var order_id = tr_obj.find("select[name=\'goods[order_id][]\']").val();
                        //var type_id = tr_obj.find("select[name=\'goods[type_id][]\']").val();
                        //var type_obj = tr_obj.find("select[name=\'goods[type_id][]\']").find("option[value=\'"+type_id+"\']");
                        //var type_text = parseFloat(type_obj.html());
                        
                    });
                });
                //删除
                function goods_del(obj) {
                    var length = $(".goods_del").parent("td").parent("tr").length;
                    
                    if(length == 1){
                        return false;
                    }
                    $(obj).parent().parent().remove();
                }
                //新增
                function goods_add(obj) {
                    var add = $(".goods").parent().parent().html();
                    add = "<tr class=\'hidden\'>"+add+"</tr>";
                    $(add).insertAfter($(".goods").parent("td").parent("tr:last"));
                    $(".goods").parent("td").parent("tr:last").find("input[name=\'goods[id][]\']").val("");
                    $(".goods").parent("td").parent("tr:last").find(".goods").val("");
                    //$(".goods").parent("td").parent("tr:last").find("span.select2").remove();
                    $(".goods").parent("td").parent("tr:last").removeClass("hidden");
                    
                    //App.initHelpers(["select2"]);
                }
            </script>';
        return ZBuilder::make('form')
            ->setPageTitle('合同加价') // 页面标题
            ->addSelect('','仅加载select插件用','', $data['equa_arr'],'','','hidden')
            ->addFormItems([ // 批量添加表单项
                ['complexTable:12', 'addprice', '', $table_data, $table_head],
            ])
            ->setExtraJs($js)
            ->setFormData($data)
            ->fetch();
    }

    /**
     * 设定面积表初始员工价格列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function UserPriceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['p.status','=',1];
        $map[] = ['t.type','<>',2];
        $order_pid = input('order_pid');
        $order_id = input('order_id');
        if(!empty($order_pid))$map[] = ['order_pid','=',$order_pid];
        if(!empty($order_id))$map[] = ['order_id','=',$order_id];
        // 数据列表
        $data_list = Db::name('mill_user_price')
            ->alias('p')
            ->field('p.*,t.type_title')
            ->leftJoin('mill_order_archives_add_price_type t','t.id=p.type_id')
            ->where($map)
            ->order('t.type asc,t.type_title asc,p.title asc,val asc,min_val asc')
            ->select();

        if(!empty($data_list)){
            foreach ($data_list as &$v){

                //条件说明
                $v['equa_str'] = FinanceModel::userPriceText($v['id']);

                $v['give_status_str'] = GiveModel::$give_status_search[$v['give_status']];
            }
        }

        $give_status_arr = GiveModel::$give_status_search;
        unset($give_status_arr[0]);

        $type_list = ClientModel::getAddPriceTypeList();
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('员工价格设置') // 页面标题
            ->setTableName('mill_user_price') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['select:2', 'p.give_status', '工艺','','',$give_status_arr],
                ['select:2', 'p.type_id', '类型','','',$type_list],
                ['text:2', 'p.title', '名称', 'like'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['give_status_str', '工艺'],
                ['type_title', '类型'],
                ['title', '名称'],
                ['equa_str', '条件'],
                ['price', '加价'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('add',['title' => '新增','href' => url('userPrice',['order_pid'=>$order_pid,'order_id'=>$order_id]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['90%', '90%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('edit',['title' => '编辑','href' => url('userPrice',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['90%', '90%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'equa_str'  => 350,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 设定面积表初始员工价格
     * @return mixed
     */
    public function UserPrice()
    {

        $id = input('id');
        $order_pid = input('order_pid');//指定工程
        $order_id = input('order_id');//指定批次

        if ($this->request->isPost()) {
            $data = $this->request->post();

            if(empty($data['give_status']))$this->error('请选择工艺');
            if(empty($data['type_id']))$this->error('请选择类型');
            if(empty($data['title']))$this->error('请填写名称');
            if(empty($data['price']))$this->error('请填写价格');

            $type_show = Db::name('mill_order_archives_add_price_type')->where(['id'=>$data['type_id']])->find();

            if($type_show['equa_type'] != 0 && empty($data['max_val']))$this->error('请填写范围');

            $data['archives_field'] = $type_show['archives_field'];

            if($id)Db::name('mill_user_price')->where(['id'=>$id])->update($data);
            else {
                if(!empty($order_pid))$data['order_pid'] = $order_pid;
                if(!empty($order_id))$data['order_id'] = $order_id;
                $id = Db::name('mill_user_price')->insertGetId($data);
            }

            //更新工程，或者批次的面积表计价
            FinanceModel::updateOrderUserPrice($id,$order_id,$order_pid);

            $this->success('操作成功','', '_parent_reload');
        }

        $info = [];
        if(!empty($id))$info = Db::name('mill_user_price')->where(['id'=>$id])->find();

        $table_head[] = [
            "<div style='text-align: center;'>工艺</div>",
            "<div style='text-align: center;'>类型</div>",
            "<div style='text-align: center;'>名称</div>",
            "<div style='text-align: center;'>指定值</div>",
            "<div style='text-align: center;'>范围</div>",
            "<div style='text-align: center;'>单件面积小于</div>",
            "<div style='text-align: center;'>加价</div>",
        ];

        $give_status_arr = GiveModel::$give_status_search;
        unset($give_status_arr[0]);

        $type_list = Db::name('mill_order_archives_add_price_type')->where('status=1')->order('type asc,type_title asc')->select();
        $type_list_new = [];
        $type_list_arr = [];
        foreach ($type_list as $k=>$v){
            $type_list_new[$v['id']] = $v;
            $type_list_arr[$v['id']] = $v['type_title'];
        }

        $readonly1 = "readonly1";
        $readonly2 = "readonly2";

        if(empty($info['min_val']) && empty($info['max_val']))$readonly2 .= ' readonly';
        else $readonly1 .= ' readonly';

        $table_data[] = [
            "[0:1]
            ".MaterialModel::inputToText('give_status',isset($info['give_status'])?$info['give_status']:'','','','select','not-js-select',$give_status_arr),
            "[0:1]
            ".MaterialModel::inputToText('type_id',isset($info['type_id'])?$info['type_id']:'','','','select','not-js-select',$type_list_arr),
            "[0:1]
            ".MaterialModel::inputToText('title',isset($info['title'])?$info['title']:'','','','input',""),
            "[0:1]
            ".MaterialModel::inputToText('val',isset($info['val'])?$info['val']:'','','','input',"{$readonly1}"),
            "[0:1]
            ".MaterialModel::inputToText('min_val',isset($info['min_val'])?$info['min_val']:'','','width: 40%;display: inline;','input',"{$readonly2}").
            "<span class='input-group-addon' style='display: inline;padding: 7px 7px 6px 7px;'> — </span>
            ".MaterialModel::inputToText('max_val',isset($info['max_val'])?$info['max_val']:'','','width: 40%;display: inline;','input',"{$readonly2}"),
            "[0:1]
            ".MaterialModel::inputToText('max_area',isset($info['max_area'])?$info['max_area']:'','','','input',""),
            "[0:1]
            ".MaterialModel::inputToText('price',isset($info['price'])?$info['price']:'','','','input',""),
        ];

        $js = '<script type="text/javascript">
                var type_list = \''.json_encode($type_list_new).'\';
                type_list = $.parseJSON(type_list);
                $(function() {
                
                    //名称事件
                    $("body").on("change","select[name=\'type_id\']",function(){
                        var tr_obj = $(this).parents("tr");
                        var type_id = tr_obj.find("select[name=\'type_id\']").val();
                        var type_show = type_list[type_id];
                        
                        if(type_show){
                            
                            //equa_type(计价类型) 0:常规计价 1:按大于小于方式计价
                            if(type_show.equa_type == 0){
                                tr_obj.find(".readonly1").prop("readonly", false);
                                tr_obj.find(".readonly1").removeClass("readonly");
                                
                                tr_obj.find(".readonly2").prop("readonly", true);
                                tr_obj.find(".readonly2").addClass("readonly");
                                tr_obj.find(".readonly2").val("");
                            }
                            else{
                                tr_obj.find(".readonly2").prop("readonly", false);
                                tr_obj.find(".readonly2").removeClass("readonly");
                                
                                tr_obj.find(".readonly1").prop("readonly", true);
                                tr_obj.find(".readonly1").addClass("readonly");
                                tr_obj.find(".readonly1").val("");
                            }
                        }
                        
                        
                    });
                });
            </script>';

        return ZBuilder::make('form')
            ->setPageTitle('加价设置') // 页面标题
            ->addFormItems([
                ['complexTable:12', 'list_archives_group', '', $table_data, $table_head]
            ])// 批量添加表单项
            ->setExtraJs($js)
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 设定面积表初始员工价格列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesUserPriceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['o.archives_status','=',2];
        //$map[] = ['o.user_price_status','=',0];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,sum(a.number) as number_sum,sum(a.one_area*a.number) as area_sum,o.id as ip_id')
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->where($map)
            ->group('o.id')
            ->order('o.archives_status_time desc,o.id desc')
            ->paginate();

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('员工单价设置') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'a.archives_sn', '档案号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum', '产品总量'],
                ['area_sum', '总面积'],
                ['user_price_status','计价状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,FinanceModel::$initial_price_status[$value]);
                    if($value == -1){
                        //$status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['initial_price_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('archivesPrice',['title' => '计价','href' => url('mill/finance/archivesUserPrice',['order_id' => '__id__']),'class'=>'btn btn-default','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 设定面积表初始员工价格
     * @return mixed
     */
    public function archivesUserPrice()
    {

        if(empty($order_id))$order_id = input('order_id');//指定工程
        if(empty($order_id))$this->error('错误操作');

        if ($this->request->isPost()) {
            $data = $this->request->post();

            $_give_scale = $data['_give_scale'];
            foreach ($_give_scale as &$sv){
                if(empty($sv))$this->error('请填写完整分配比例');
            }
            $give_scale = $_give_scale;

            //更新员工单价
            if(!empty($data['user_price_setting'])){
                foreach ($data['user_price_setting'] as $pk => $pv){

                    //获取扫码记录，并更新扫码记录的员工单价和分配比例
                    $log_where = ['order_id'=>$order_id,'status'=>$pk];
                    $log_list = Db::name('mill_order_archives_give_log')->where($log_where)->select();
                    if(!empty($log_list)){
                        foreach ($log_list as $lv){

                            //根据联合扫码人数，获取对应的分配比例设置
                            $scale_setting = FinanceModel::orderGiveScale($give_scale,$lv['scale_count']);
                            //根据分配比例等级，获取分配比例
                            $scale = $scale_setting[$lv['scale_level']];
                            //根据板型类型，获取对应单价
                            $user_price = $pv["price{$lv['model_type']}"];
                            $lv_price = $user_price * ($scale/100);
                            $log_update = [
                                'scale_setting'     =>  implode(",",$scale_setting),//分配比例设置
                                'scale'             =>  $scale,//分配比例
                                'user_price'        =>  $user_price,//单价
                                'price'             =>  $lv_price,//实际金额
                            ];
                            Db::name('mill_order_archives_give_log')->where(['id'=>$lv['id']])->update($log_update);
                        }
                    }

                }

                //更新计价状态
                $update = [
                    'user_price_status'         =>  2,
                    'user_price_setting'        =>  json_encode($data['user_price_setting'],JSON_UNESCAPED_UNICODE),
                    'give_scale'                =>  implode("\r\n",$_give_scale)
                ];
                Db::name('mill_order')->where(['id'=>$order_id])->update($update);

            }

            $this->success('编辑成功', cookie('__forward__'));
        }

        $table_arr = FinanceModel::fromArchivesUserTable($order_id);

        $where[] = ['a.order_id','=',$order_id];

        //单价设置
        $order = $table_arr['order_info'];
        $title = "{$order['engineering']} {$order['archives_sn']} 员工单价设置";

        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];
        $js = $table_arr['js'];

        $js .= '<script type="text/javascript">
                $(function() {
                    $("input[name=\'finance_type\']").click(function() {
                        var val = $(this).val();
                        $(".finance").hide();
                        $(".finance").removeClass("hidden");
                        $(".finance[data-type=\'"+val+"\']").show();
                    });
                })
            </script>';

        // 批量添加表单项
        $formItems = [];

        $give_scale = config('mill_give_scale');
        if(!empty($order['give_scale']))$order['give_scale'] = explode("\r\n",$order['give_scale']);
        $i = 0;
        foreach ($give_scale as $sk=>$sv){
            if(isset($order['give_scale'][$i]))$sv = $order['give_scale'][$i];

            $masked = preg_replace('/\d/', '9', $sv);//设置固定格式
            $formItems[] = ['masked', "_give_scale[{$i}]", $sk, '', $masked,$sv];

            $i++;
        }
        //['number', '_ingots_price', '铝锭价', '', $archives_price['ingots_price']],
        //['text', '_ingots_time', '铝锭价日期', '', $archives_price['ingots_time']],
        //['complexTable:12', 'contract', '', $table_contract_data, $table_contract_head],
        $formItems[] = ['complexTable:3', 'list_archives_group', '', $table_data, $table_head];

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addFormItems($formItems)// 批量添加表单项
            ->setExtraJs($js)
            ->fetch();
    }

    /**
     * 员工价格结算列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function userGiveLogList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        if(!empty($map)){
            foreach ($map as $m_v_i=>$m_v){
                if(in_array('a_sort',$m_v)){
                    $a_sort = explode('-',$m_v[2]);
                    $sort = !empty($a_sort[0])?$a_sort[0]:'';
                    $counter = !empty($a_sort[1])?$a_sort[1]:'';
                    unset($map[$m_v_i]);
                }
                elseif($m_v[0] == 'g.status'){
                    $archives_status = $m_v[2];
                    if(count(explode(',',$archives_status)) > 1){
                        $archives_status = explode(',',$archives_status)[0];
                    }
                }

            }
        }
        $map = array_merge($map);
        if(!empty($sort))$map[] = ['a.sort','=',$sort];
        if(!empty($counter))$map[] = ['g.counter','=',$counter];
        //生产状态：0待生产，1开平，2开料，3折弯，4组装，5发货

        //获取所有负责人
        $user_list = UserModel::getList();
        //unset($user_list[0]);
        //unset($user_list[1]);

        $data_list = [];
        $data_stat = [
            'number_sum'        =>  0,
            'area_sum'          =>  0,
        ];
        $data_user_stat[] = ['id'=>0,'scale'=>'合计数量','price'=>"合计金额"];

        if(!empty($map)){
            // 数据列表
            $data_list = Db::name('mill_order_archives_give_log')
                ->alias('g')
                ->field("g.*,o.batch,o.order_sn_off as o_batch,a.model,a.model_sn,a.thickness,a.one_area,a.color,a.sort as a_sort,o.engineering")
                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                ->leftJoin('mill_order o','o.id=g.order_id')
                ->where($map)
                ->order('status_time desc')
                ->select();

            if(!empty($data_list)){
                foreach ($data_list as &$v){

                    //扫码人名称
                    $v['nickname'] = $user_list[$v['status_uid']];
                    //序号
                    $v['a_sort'] = "{$v['a_sort']}-{$v['counter']}";

                    //是否质检后扫的码
                    $v['is_quality'] = !empty($v['is_quality'])?'<span class="label label-primary">质检后扫码</span>':'';

                    //是否补扫
                    $v['is_bu'] = !empty($v['is_bu'])?'<span class="label label-primary">补扫</span>':'';

                    $data_stat['number_sum'] ++;
                    $data_stat['area_sum'] += $v['one_area'];

                    if(empty($data_user_stat["_{$v['status_uid']}"])){
                        //$data_user_stat["_{$v['status_uid']}"] = [
                        $data_user_stat["_{$v['status_uid']}"] = [
                            'id'                =>  0,
                            'nickname'          =>  $v['nickname'],
                            'scale'             =>  0,
                            'price'             =>  0,
                        ];
                        //dump($data_user_stat);
                    }
                    $data_user_stat["_{$v['status_uid']}"]['scale'] ++;//累计扫码数量
                    $data_user_stat["_{$v['status_uid']}"]['price'] += $v['price'];//累计金额

                }
            }

            $data_list = array_merge($data_list,$data_user_stat);
        }

        $title = '员工工资管理';
        if(!empty($archives_status))$title = GiveModel::$give_status[$archives_status]." {$title}";

        $print_title = $title;
        $title .= '（总数量'.$data_stat['number_sum'].'/总面积'.$data_stat['area_sum'].'M²）';

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$print_title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        //导出按钮
        $print_btn = ['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print'];

        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order_archives_give_log') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['select:1', 'g.status', '工位', '', '', GiveModel::$give_status_search],
                ['text:2', 'g.archives_sn', '档案编号', 'like'],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['text:2', 'give_sn', '条码编号', 'like'],
                ['text:2', 'a_sort', '序号查询'],
                ['text:3', 'a.model_sn', '铝板编号', 'like'],
                ['select:2', 'g.status_uid', '扫码人', 'like', '', $user_list],
                ['select:2', 'g.is_bu', '是否查看补扫', 'like', '', [0=>'不要补扫',1=>'要补扫']],
                ['daterange:2', 'g.status_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案编号'],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['model_sn', '铝板编号'],
                ['color', '颜色'],
                ['a_sort','序号'],
                ['give_sn', '产品条形码编号'],
                ['model', '铝板版型'],
                ['one_area', '面积M²'],
                ['user_price', '单价'],
                ['nickname', '扫码人'],
                ['scale', '分配比例'],
                ['price', '实际金额','text.edit'],
                ['is_bu','补扫'],
                ['status_time','扫码时间','datetime'],
                //['is_quality', '备注', 'status', '', ['1', '质检后扫码']],
                ['is_quality', '备注'],
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            //->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print'])
            ->addTopButton('ablequality',$print_btn)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'thickness'  => 50,
                'number'  => 30,
                'one_area'  => 50,
                'a_sort'  => 60,
                'give_sn'  => 110,
                'status'  => 60,
                'batch'  => 60,
                'is_bu'  => 60,
                'scale'  => 60,
                'user_price'  => 60,
                'price'  => 60,
                'engineering'  => 150,
            ])
            //->noPages()
            ->fetch(); // 渲染模板
    }

    /**
     * 收款记录
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function logList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $finance_id = input('finance_id');
        $map = $this->getMap();
        $map[] = ['l.finance_id','=',$finance_id];

        // 数据列表
        $data_list = Db::name('mill_finance_log')
            ->alias('l')
            ->field('l.*,o.engineering,c.company,o.order_sn')
            ->leftJoin('mill_order o','o.id=l.order_pid')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where($map)
            ->group('l.id')
            ->order('l.id desc')
            ->paginate()
            ->each(function ($v){
                $v['money_str'] = FinanceModel::getMoneyStr($v['type'],$v['money'],true);
                $v['money'] = FinanceModel::getMoneyStr($v['type'],$v['money']);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('收款记录（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_finance_log') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                //['text:2', 'f.order_sn', '工程编号', 'like'],
                //['text:2', 'o.engineering', '工程名称', 'like'],
                //['text:2', 'c.company', '客户公司', 'like'],
                //['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['money_str','收款金额(元)'],
                ['note', '收款说明'],
                ['handle', '经办人'],
                /*['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],*/
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('logAdd',['title' => '新增','href' => url('logAdd',['finance_id'=>$finance_id]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('logEdit',['title' => '编辑','href' => url('logAdd',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function logAdd()
    {
        $id = input('id');
        $finance_id = input('finance_id');

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $rule = [
                'finance_id|标题' => 'require',
                //'type|收入类型' => 'require',
                'money|收款金额' => 'require',
                'handle|经办人' => 'require',
                'note|说明' => 'require',
            ];
            $result = $this->validate($data, $rule);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['update_time'] = time();

            if($id)$re = Db::name('mill_finance_log')->where(['id'=>$id])->update($data);
            else{
                $data['create_time'] = time();
                $re = Db::name('mill_finance_log')->insert($data);
            }

            if ($re) $this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        if($id){
            $info = Db::name('mill_finance_log')
                ->alias('f')
                ->field('f.*,o.order_sn,o.engineering')
                ->leftJoin('mill_order o','o.id=f.order_pid')
                ->where(['f.id'=>$id])
                ->find();
        }
        else{
            $finance = Db::name('mill_finance')
                ->alias('f')
                ->field('f.*,o.order_sn,o.engineering')
                ->leftJoin('mill_order o','o.id=f.order_pid')
                ->where(['f.id'=>$finance_id])
                ->find();

            $info = [
                'finance_id'    =>  $finance_id,
                'order_pid'     =>  $finance['order_pid'],
                'order_sn'      =>  $finance['order_sn'],
                'engineering'   =>  $finance['engineering'],
            ];
        }

        return ZBuilder::make('form')
            ->setPageTitle('新增收款记录') // 页面标题
            ->addStatic('order_sn','工程号')
            ->addStatic('engineering','工程名称')
            ->addFormItems([ // 批量添加表单项
                ['hidden','finance_id'],
                ['hidden','order_pid'],
                ['hidden','order_sn'],
                //['radio:||||must','type', '收入类型','',['调减收入','调增收入'],1],
                ['text:||||must', 'money', '收款金额'],
                ['text:||||must', 'handle', '经办人'],
                ['textarea:||||must', 'note', '收款说明'],

            ])
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 开票汇总
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function invoiceStat()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $finance_id = input('finance_id');
        $map = $this->getMap();

        // 数据列表
        $data_list = Db::name('mill_finance_invoice')
            ->alias('f')
            ->field('f.*')
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate()
            ->each(function ($v){
                $v['money_str'] = FinanceModel::getMoneyStr($v['type'],$v['money'],true);
                $v['money'] = FinanceModel::getMoneyStr($v['type'],$v['money']);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('发票汇总（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_finance_invoice') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '工程编号', 'like'],
                ['text:2', 'f.engineering', '工程名称', 'like'],
                ['text:2', 'f.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                ['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['model','规格'],
                ['model_num','数量'],
                ['invoice_sn','票号'],
                ['invoice_time','开票日期','date'],
                ['money_str','开票金额(元)'],
                ['note', '开票说明'],
                ['handle', '经办人'],
                /*['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],*/
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('invoiceEdit',['title' => '编辑','href' => url('invoiceAdd',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 开票记录
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function invoiceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $finance_id = input('finance_id');
        $map = $this->getMap();
        $map[] = ['finance_id','=',$finance_id];

        // 数据列表
        $data_list = Db::name('mill_finance_invoice')
            ->alias('f')
            ->field('f.*')
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate()
            ->each(function ($v){
                $v['money_str'] = FinanceModel::getMoneyStr($v['type'],$v['money'],true);
                $v['money'] = FinanceModel::getMoneyStr($v['type'],$v['money']);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('开票记录（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_finance_invoice') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                //['text:2', 'f.order_sn', '工程编号', 'like'],
                //['text:2', 'o.engineering', '工程名称', 'like'],
                //['text:2', 'c.company', '客户公司', 'like'],
                //['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['model','规格'],
                ['model_num','数量'],
                ['invoice_sn','票号'],
                ['invoice_time','开票日期','date'],
                ['money_str','开票金额(元)'],
                ['note', '开票说明'],
                ['handle', '经办人'],
                /*['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],*/
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('invoiceAdd',['title' => '新增','href' => url('invoiceAdd',['finance_id'=>$finance_id]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('invoiceEdit',['title' => '编辑','href' => url('invoiceAdd',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function invoiceAdd()
    {
        $id = input('id');
        $finance_id = input('finance_id');

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $rule = [
                //'type|收入类型' => 'require',
                'money|调账收入' => 'require',
                'handle|经办人' => 'require',
                'note|调账说明' => 'require',
            ];
            $result = $this->validate($data, $rule);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['invoice_time'] = strtotime($data['invoice_time']);
            $data['update_time'] = time();

            if($id)$re = Db::name('mill_finance_invoice')->where(['id'=>$id])->update($data);
            else{
                $data['create_time'] = time();
                $re = Db::name('mill_finance_invoice')->insert($data);
            }

            if ($re) $this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        if($id){
            $info = Db::name('mill_finance_invoice')
                ->alias('f')
                ->field('f.*,o.order_sn,o.engineering')
                ->leftJoin('mill_order o','o.order_sn=f.order_sn')
                ->where(['f.id'=>$id])
                ->find();
        }
        else{
            $finance = Db::name('mill_finance')
                ->alias('f')
                ->field('f.*,o.order_sn,o.engineering')
                ->leftJoin('mill_order o','o.id=f.order_pid')
                ->where(['f.id'=>$finance_id])
                ->find();

            $info = [
                'finance_id'      =>  $finance_id,
                'order_pid'      =>  $finance['order_pid'],
                'order_sn'      =>  $finance['order_sn'],
                'engineering'   =>  $finance['engineering'],
            ];
        }

        return ZBuilder::make('form')
            ->setPageTitle('新增开票记录') // 页面标题
            ->addStatic('order_sn','工程号')
            ->addStatic('engineering','工程名称')
            ->addFormItems([ // 批量添加表单项
                ['hidden','finance_id'],
                ['hidden','order_pid'],
                ['hidden','order_sn'],
                //['radio:||||must','type', '收入类型','',['调减收入','调增收入'],1],
                ['text:||||must', 'model', '规格'],
                ['text:||||must', 'model_num', '数量'],
                ['text:||||must', 'invoice_sn', '票号'],
                ['date:||||must', 'invoice_time', '开票日期','',date('Y-n-d')],
                ['text:||||must', 'money', '开票金额'],
                ['text:||||must', 'handle', '经办人'],
                ['textarea:||||must', 'note', '开票说明'],

            ])
            ->setFormData($info)
            ->fetch();
    }
}
